<template>
  <div :class="keyboardClass"></div>
</template>

<script lang="ts">
import Keyboard from 'simple-keyboard';
import 'simple-keyboard/build/css/index.css';
import layout from 'simple-keyboard-layouts/build/layouts/chinese'; // 中文输入法
import {setValFn} from '@/utils/core'

export default {
  name: 'SimpleKeyboard',
  props: {
    keyboardClass: {
      default: 'simple-keyboard',
      type: String
    },
    input: {
      default: ''
    },
    maxlength: { default: 250 },
    inputType:{
      default: 'text',
      type:String
    },
    precision:{
      default: 2
    }
  },
  data: () => ({
    keyboard: null,
    displayDefault: {
      '{bksp}': 'backspace',
      '{lock}': 'caps',
      '{enter}': '> enter',
      '{tab}': 'tab',
      '{shift}': 'shift',
      '{change}': '英文',
      '{space}': ' ',
      '{clear}': 'Empty',
      '{close}': '关闭'
    },
    firstOpen:false
  }),
  computed:{
    layout(){
      if(this.inputType==='number'){
        return {
          default: ["1 2 3", "4 5 6", "7 8 9", "+/- 0 .",
          "{bksp} {clear}",
          // " {enter}"
          ],
          shift: ["! / #", "$ % ^", "& * (", "{shift} ) +", "{bksp} {clear}"]
        }
      }

      return {
        // 默认布局
        default: [
          '` 1 2 3 4 5 6 7 8 9 0 - = {bksp}',
          '{tab} q w e r t y u i o p [ ] \\',
          // "{lock} a s d f g h j k l ; ' {enter}",
          "{lock} a s d f g h j k l ; '",
          '{shift} z x c v b n m , . / {clear}',
          // '{change} {space} {close}'
        ],
        // shift布局
        shift: [
          '~ ! @ # $ % ^ & * ( ) _ + {bksp}',
          '{tab} Q W E R T Y U I O P { } |',
          '{lock} A S D F G H J K L : "',
          // '{lock} A S D F G H J K L : " {enter}',
          '{shift} Z X C V B N M < > ? {clear}',
          // '{change} {space} {close}'
        ]
      }
    }
  },
  mounted() {
    // console.log(this.maxlength)
    this.keyboard = new Keyboard(this.keyboardClass, {
      onChange: this.onChange,
      onKeyPress: this.onKeyPress,
      layoutCandidates: (layout as any).layoutCandidates,
      layout: this.layout,
      // 按钮展示文字
      display: this.displayDefault,
      // 按钮样式
      buttonTheme: [
        {
          class: 'hg-red close',
          buttons: '{close}'
        },
        {
          class: 'change',
          buttons: '{change}'
        }
      ],
      // 输入限制长度
      maxLength: this.maxlength
    });

    this.$nextTick(() => {
      this.keyboard.setInput(this.input);

      this.firstOpen = true;
    });
  },
  methods: {
    onChange(input) {
      // this.firstOpen && (this.firstOpen = false);

      this.keyboard.setInput(setValFn(this.inputType,input,this.firstOpen,this.precision));

      this.$emit('onChange', setValFn(this.inputType,input,this.firstOpen,this.precision));

      this.firstOpen && (this.firstOpen = false);
    },
    // 点击键盘
    onKeyPress(button, $event) {
      // console.log(button)

      // 点击关闭
      if (button === '{close}') {
        this.firstOpen && (this.firstOpen = false);

        let keyboard = $event.path[3];
        keyboard.style.visibility = 'hidden';

        return false;
      } else if (button === '{change}') {
        // 切换中英文输入法
        this.firstOpen && (this.firstOpen = false);

        if (this.keyboard.options.layoutCandidates !== null) {
          this.displayDefault['{change}'] = '中文';
          // this.$set(this.displayDefault, '{change}', '中文');
          // 切换至英文
          this.keyboard.setOptions({
            layoutCandidates: null,
            display: this.displayDefault
          });
        } else {
          // 切换至中文
          this.displayDefault['{change}'] = '英文';
          // this.$set(this.displayDefault, '{change}', '英文');
          this.keyboard.setOptions({
            layoutCandidates: (layout as any).layoutCandidates,
            display: this.displayDefault
          });
        }


      } else if (button === '{clear}') {
        this.firstOpen && (this.firstOpen = false);

        this.keyboard.clearInput();


      } else if (button === '{bksp}'){
        let value =
          this.input;

        this.firstOpen && (this.firstOpen = false);

        this.onChange(value.slice(0,value.length-1));
      }else if (button === '+/-'){
        let value = this.input;

        if(value && value.length){
          let t = value.charAt(0);

          if(t === '-'){
            value = value.slice(1,value.length);
          }else{
            if(value !== '0'){
              value = '-' + value;
            }
          }
          this.onChange(value);
        }

        this.firstOpen && (this.firstOpen = false);
      } else {
        // if(this.firstOpen){
        //   this.onChange(button);

        //   // this.firstOpen = false;

        //   return;
        // }

        // let value =
        //   $event.target.offsetParent.parentElement.children[0].children[0].children[0].children[0]
        //     .value;

        let value = (document.querySelector('.DFKeyboardInputView .n-input__input-el') as any).value

        // 输入框有默认值时，覆写
        // console.log($event.target.offsetParent.parentElement.children[0].children[0].children[0].children[0])
        if (value) {
          this.keyboard.setInput(value);
        }

        this.$emit('onKeyPress', button);
      }

      if (button === '{shift}' || button === '{lock}'){
        this.handleShift();

        this.firstOpen && (this.firstOpen = false);
      }


    },
    // 切换shift/默认布局
    handleShift() {
      let currentLayout = this.keyboard.options.layoutName;
      let shiftToggle = currentLayout === 'default' ? 'shift' : 'default';

      this.keyboard.setOptions({
        layoutName: shiftToggle
      });
    },
  },
  watch: {
    input: {
      handler: function (input) {
        if (this.keyboard) {
          this.keyboard.setInput(setValFn(this.inputType,input,this.firstOpen,this.precision));
        }
      },
      deep: true,
      immediate: true
    }
  }
};
</script>

<style lang="less">
@deep: ~'>>>';
.hg-theme-default {
  // width: 70%;
  position: relative;
  z-index: 100;
  // .hg-button {
  //   &.hg-red {
  //     background: #db3e5d;
  //     color: white;
  //     &.close {
  //       max-width: 200px;
  //     }
  //   }
  //   &.change {
  //     max-width: 200px;
  //   }
  // }
  .hg-button{
    transition: .5s background-color;
    &:active{
      background-color: #307AFA;
      transition: .5s background-color;
    }
  }
}

.DFModalKeyboard,.DFModalKeyboardModal{
  .hg-button{
    height: 76px;
    font-size: 26px;
  }
}

.DFKeyboardInput-style4{
  .hg-button{
    transition: .5s background-color;
    &:active{
      background-color: #207af6;
      transition: .5s background-color;
    }
  }
}
</style>
